//公共方法
var buildUrl = function(type, module, method, params, fromcustomerId) {
    if (typeof(fromcustomerId) == "undefined") {
        var cus = document.getElementById('customerId').value;
    } else {
        var cus = fromcustomerId;
    }

    params = encodeURIComponent(JSON.stringify(params));
    var _URL = "call." + type + "?customerId=" + cus + '&module=' + module + '&method=' + method + '&params=' + params;
    return _URL;
}
var fee = $("#fee").val(),
    activityname = $("#activityname").val(),
    actId = $("#actId").val(),
    customerId=$("#customerId").val(),
    is_send_location=$("#is_send_location").val();
//微信支付
var WX = {
    /*
     * 获取微信支付参数
     * oid:订单id
     * desc:商品描述显示在微信支付界面中
     * productFee:产品价格
     * module:回调模块
     * moduleId:回调模块id
     * transportFee:运费单位分
     * userName:用户openid
     * method:回调方法
     */
    WxPayParamAjax: function(oid, desc, productFee, module, moduleId, transportFee, userName, method, callback) {


        var urlString = baseUrl + 'Wxpay/getWxPayParam.json?customerId='+customerId;


        var me = this;
        $.ajax({
            url: urlString,
            dataType: "json",
            type: "post",
            data: {
                'sn': 0,
                'desc': desc,
                'productFee': productFee,
                'module': module,
                'moduleId': moduleId,
                'transportFee': transportFee,
                'userName': userName,
                'method': method
            },
            success: function(d) {
                $.util.pageLoading.hide();
                if (d.code) {
                    // $.util.alert(d.msg);
                    return;
                }
                WeixinJSBridge.invoke('getBrandWCPayRequest', d.pkg, function(res) {
                    WeixinJSBridge.log(res.err_msg);
                    if (res.err_msg == 'get_brand_wcpay_request:ok') {
                        if (typeof(callback) == "function") {
                            callback();
                        }
                    } else {
                        var res = res;
                        if (res.err_msg == 'get_brand_wcpay_request:cancel') {
                            return alert("操作已取消"), void 0
                        } else if (res.err_msg == 'get_brand_wcpay_request:fail') {
                            return alert("网络错误发送失败，请稍后再试"), void 0
                        } else if (res.err_msg == 'access_control:not_allow' || res.err_msg == 'system:access_denied') {
                            return alert("商家尚未开通微信支付"), void 0
                        } else {
                            return alert(res.err_msg), void 0
                        }
                    }
                });
            },
            error: function() {
                alert('支付失败');
            }
        });
    },
};
var clickByClass = function(selector, _class, callback) {
    if (selector.hasClass(_class) || selector.parents(_class).length != 0) {
        if (typeof(callback) != "undefined") {
            callback();
        }
    }
}

var check = function(arr) {
    var bool = true;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].isNeed == '1' && !arr[i].value) {
            bool = false;
            if(arr[i].info)
            var content=arr[i].info
            else
            var content="请输入"+arr[i].itemName
            layer.open({
                content:content
            });
            break;
        }
    }
    return bool;
}

var deleteArr = function(arr) {
        for (var i = 0; i < arr.length; i++) {
            delete arr[i].isNeed;
            delete arr[i].info;
        }
        return arr;
    }
//获取地理位置
var getLocation=function(callback)
{
    wx_share.getLocation(function(latitude,longitude,speed,accuracy){
        if(typeof(callback)!="undefined")
        {
            callback(latitude,longitude)
        }
    })
}
var uploadPic=function(e)
{
    var $this=$(this);
    // var img=new Image();
    // img.src="http://oss.mboxone.com/20170506/image/3/1494056033100685.jpg";
    // $this.html(img);
    // $this.attr("data-value","http://oss.mboxone.com/20170506/image/3/1494056033100685.jpg");
    wx_share.uploadMultImage(function(data) {
         data=JSON.parse(data);
         var img=new Image();
         img.src=data.path+"@320h_320w_1c_1e";
         $this.html(img);
         $this.attr("data-value",data.path);
    });
}


    //提交报名
var postEntry = function(obj,obj1) {
        var link = buildUrl("json", "enroll", "confirmEnroll", {
            lat:obj1.latitude?obj1.latitude:"",
            lng:obj1.longitude?obj1.longitude:"",
            actId: $.util.getParamByObject("actId"),
            form_json_str : obj,
            chanelId:$.util.getParamByObject("chanelId")?$.util.getParamByObject("chanelId"):"",
            fromUserId:$.util.getParamByObject("fromUserId")?$.util.getParamByObject("fromUserId"):""
        })
        $.ajax({
            url: link,
            dataType: "json",
            type: "get",
            beforeSend: function() {
                layer.open({ type: 2 });
            },
            success: function(data) {
                layer.closeAll();
                if (data.status == "success") {
                    if(fee)
                    {
                        layer.open({
                            content:"提交表单成功，进入支付阶段"
                        });
                        WX.WxPayParamAjax(0, activityname, fee, "enroll", actId, 0, userName, "payCallBack", function() {
                            successForm();
                        });
                    }
                    else
                    {
                        successForm();
                    }
                    
                }
                else
                {
                    layer.open({
                        content:data.message
                    });
                }
            }
        })
    }
    //判断状态以及关注
var getStatus = function() {
    var link = buildUrl("json", "enroll", "preEnroll", {
        actId: $.util.getParamByObject("actId"),
        chanelId: $.util.getParamByObject("chanelId")?$.util.getParamByObject("chanelId"):""
    })
    $.ajax({
        url: link,
        dataType: "json",
        type: "get",
        beforeSend: function() {
            layer.open({ type: 2 });
        },
        success: function(data) {
            layer.closeAll();
            if(data.status=="success")
            {
                 layer.open({
                    content: template("entryForm", entryFormArray.formValue),
                    style: 'width:92%',
                    shadeClose: false
                });
                closeBtn();
                submitForm();
            }
            else 
            {
              if(data.message=="请先关注")
              {
                guanzhu();
              }
              else
              {
                layer.open({
                    content:data.message
                })
              }
            
            }
            // layer.open({
            //     content: template("entryForm", entryFormArray.formValue),
            //     style: 'width:80%',
            //     shadeClose: false
            // });
            // closeBtn();
            // submitForm();
        }
    })
}
var guanzhu=function(){
    var html = template("need_subscribe", {});
    layer.open({
        content:html,
        style:"width:80%",
        shadeClose:true
    })
    closeBtn();
}
var successForm = function() {
    var html = template("successForm", {});
    layer.open({
        content: html,
        style: 'width:80%',
        shadeClose: false
    });
    shareBtn();
    closeBtn();

}
var submitForm=function(){
    $(".upload").unbind().on("click",uploadPic);
    $(".submitform").unbind().on('click',function(){
         var results = new Array(),
            iswork = true;
        $("[formjson]").each(function(index) {
            var $this = $(this),
                itemName = $this.attr("itemName"),
                itemType = $this.attr("itemType"),
                isNeed = $this.attr("data-need"),
                info = $this.attr("data-info"),
                value = $this.val()?$this.val():$this.attr("data-value");
            var str = {
                itemName: itemName,
                itemType: itemType,
                isNeed: isNeed,
                info: info,
                value: typeof(value) == "undefined" ? $this.attr("data-value") : value
            }
            results.push(str)
        })
        console.log(results);
        if (check(results)) {
            results = deleteArr(results);
            if(is_send_location=="1")
            {
                getLocation(function(latitude,longitude){
                    postEntry(results,{
                        latitude:latitude?latitude:"",
                        longitude:longitude?longitude:""
                    });
                })
            }
            else
            {
                postEntry(results,{});
            }
            
            
        }
    })
   
}
var closeBtn=function(){
    $(".closebtn").unbind().on('click',function(){
        layer.closeAll();
        $(".sharebg").hide();
    })
}
var shareBtn=function(){
    $(".sharebtn").unbind().on('click',function(){
        $('.layermbox .sharebg').remove();
        var share=$('.sharebg').clone();
        $(".layermbox").append(share)
        $('.layermbox .sharebg').show();
    })
}
var entry = function() {
    for (var i = 0; i < entryFormArray.formValue.length; i++) {
        var item = entryFormArray.formValue[i];
        item.itemType = JSON.parse(item.itemType);
    }
    entryFormArray.activity_index_img.src = entryFormArray.activity_index_img.src.split(",");
    var html = template("activity_index_img_tpl", {data:entryFormArray.activity_index_img.src});
    $("#activity_index_img").html(html);
    console.log(html)
    $(".preSubmit").on('click',function(){
        getStatus();
    })
}
$(function() {
    entry();
})
